#include "mqttclient.h"
#include "common/configmanager/configmanager.h"
#include "log/log.h"
std::shared_ptr<CMqttClient> CMqttClient::m_InStance= nullptr;
std::once_flag CMqttClient::m_flag;
CMqttClient::CMqttClient(QObject *parent)
    : QObject{parent}, m_broker(""),
    m_userName(""),
    m_PubTopic1(""),
    m_port(1883),
    m_password(""),
    m_robotSn(""),
    m_robotIp(""),
    m_ImagesDataTopic("")
{
    m_MqttClient = new QMqttClient(this);
//初始化
//    m_keepAliveTimer(new QTimer(this)){
//        setupClient();
//    }

}
std::shared_ptr<CMqttClient> CMqttClient::GetInstance() {
    std::call_once(m_flag, []() {
        m_InStance = std::shared_ptr<CMqttClient>(new CMqttClient(),
                                                    [](CMqttClient* ptr){delete ptr;});
    });

    return m_InStance;
}
CMqttClient::~CMqttClient(){
    if(m_keepAliveTimer->isActive()){
        m_keepAliveTimer->stop();
    }
    delete m_MqttClient; // 清理
    m_MqttClient = nullptr;
}

void CMqttClient::setupClient(){
    //初始化m_mqttClient并连接信号与槽
    connect(m_MqttClient, &QMqttClient::connected, this, &CMqttClient::onConnected);
    connect(m_MqttClient, &QMqttClient::disconnected, this, &CMqttClient::onDisconnected);
    connect(m_MqttClient, &QMqttClient::messageReceived, this, &CMqttClient::onMessageReceived);

}
void CMqttClient::init(){
    //初始化读取配置文件
    std::shared_ptr<CConfigManager> pIntance = CConfigManager::GetInstance();
    if(nullptr !=pIntance){
        std::string strPath = "E:\\wlr\\cfg\\json.cfg";
        Json::Value tempValue = Json::Value::null;
        if (!pIntance->loadConfig(strPath, tempValue)) {
            LOG_ERROR("Loading Config error!");
            return;
        }else{
            if (tempValue.isMember("MQTT") && tempValue["MQTT"].isObject()){
                qDebug() << "================== MQTT " << tempValue["MQTT"].toStyledString().c_str();
                if (tempValue["MQTT"].isMember("broker") && tempValue["MQTT"]["broker"].isString()){
                    m_broker = tempValue["MQTT"]["broker"].asCString();
                    qDebug() << "======== " <<tempValue["MQTT"]["broker"].toStyledString().c_str();
                }
                if(tempValue["MQTT"].isMember("port") && tempValue["MQTT"]["port"].isInt()){
                    m_port = tempValue["MQTT"]["port"].asInt();
                }
                if(tempValue["MQTT"].isMember("username") && tempValue["MQTT"]["username"].isString()){
                    m_userName = tempValue["MQTT"]["username"].asCString();
                }
                if(tempValue["MQTT"].isMember("password") && tempValue["MQTT"]["password"].isString()){
                    m_password = tempValue["MQTT"]["password"].asCString();
                }
                if(tempValue["MQTT"].isMember("topic") && tempValue["MQTT"]["topic"][0].isString()){
                    m_SubTopic1 = tempValue["MQTT"]["topic"][0].asString(); //发布的主题
                }
                if(tempValue["MQTT"]["topic"].size() > 1){
                    if(tempValue["MQTT"].isMember("topic") && tempValue["MQTT"]["topic"][1].isString()){
                        m_takeOverTopic = tempValue["MQTT"]["subtopic"][1].asString(); //发布的主题
                    }
                }
            }
        }
    }
    //初始化m_mqttClient并连接信号与槽
    connect(m_MqttClient, &QMqttClient::connected, this, &CMqttClient::onConnected);
    connect(m_MqttClient, &QMqttClient::disconnected, this, &CMqttClient::onDisconnected);
    connect(m_MqttClient, &QMqttClient::messageReceived, this, &CMqttClient::onMessageReceived);
}
void CMqttClient::Connect(const QString &broker, int port, const QString &username, const QString &password){
    if(!m_MqttClient){
        m_MqttClient = new QMqttClient(this);
    }

    m_MqttClient->setHostname(broker);
    m_MqttClient->setPort(port);
    m_MqttClient->setUsername(username);
    m_MqttClient->setPassword(password);
    m_MqttClient->connectToHost();
}
void CMqttClient::Subscribe(const QString &topic){
    if (m_MqttClient->subscribe(topic)){
       subscribedTopics.push_back(topic);
    }else {
       qDebug() <<"Failed to subscribe to topic: " <<topic;
    }
}
void CMqttClient::Unsubscribe(const QString &topic){
    m_MqttClient->unsubscribe(topic);
    subscribedTopics.removeAll(topic);
}
void CMqttClient::Publish(const QString &topic, const QByteArray &message){
    if (!m_MqttClient->publish(topic, message, 0, false)) {
       qDebug() <<"Failed to publish message to topic: "  <<  topic;
    }
}

void CMqttClient::onConnected(){

}
void CMqttClient::onDisconnected(){
    qDebug() <<"Disconnected from MQTT Broker.";
    if(m_keepAliveTimer->isActive()){
       m_keepAliveTimer->stop();
    }
}
void CMqttClient::processMsg(const QString &topic, const QByteArray &message){
    if (topic == m_ImagesDataTopic.c_str()) {
      // CImgSource::GetInStance()->processData(message);
    }else if (topic == "WLRobotics" || topic == "TakeOver"){
      //修改控制信息
      QString msgStr = QString::fromUtf8(message);
      if (topic == "WLRobotics") {
            emit SendBasicDatas(msgStr);
      } else if (topic == "TakeOver") {
            emit SendTakeOverInfo(msgStr);
      }
    }
}
//启动连接Mqtt客户端的连接
void  CMqttClient::Start(){
    Connect(m_broker, m_port, m_userName, m_password);
}
